package cn.shengchao.event.userinfo.collect;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import cn.shengchao.base.event.userinfo.UserInfoBatchCollectEvent;
import cn.shengchao.base.event.userinfo.UserInfoSingleCollectEvent;
import cn.shengchao.base.event.userinfo.UserInfoCollectType;
import cn.shengchao.examstar.distribute.infrastrure.po.DistributeNodeInfo;
import cn.shengchao.examstar.distribute.infrastrure.service.DistributeNodeInfoService;
import cn.shengchao.examstar.me.collect.acl.ports.repositories.IUserCollectInfoRepository;
import cn.shengchao.examstar.me.infrastructure.dao.po.UserCollectInfo;
import cn.shengchao.examstar.rpc.distribute.enums.DistributeSaleRoleEnum;
import cn.shengchao.examstart.user.acl.ports.repositories.IUserRepository;
import cn.shengchao.examstart.user.domain.entity.User;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @program: examstarapi
 * @description: 用户信息采集
 * @author: Xiong weiqiang
 * @create: 2025-04-14 14:34
 */
@Component
public class UserInfoCollectListener {
    @Autowired
    IUserRepository userRepository;
    @Autowired
    IUserCollectInfoRepository userCollectInfoRepository;
    @Autowired
    DistributeNodeInfoService distributeNodeInfoService;
    /** 
     * method : onApplicationEvent
     * description :     用户信息采集事件
     * @param userInfoSingleCollectEvent \{@link UserInfoSingleCollectEvent \}
     * @author : Xiong weiqiang 
     * @CreateDate : 2025-04-14 14:42:27
     *  
     * @Reviewed : 
     * @UpdateLog :    Name    Date    Reason/Contents
     *             ---------------------------------------
     *                ****    ****    **** 
     *
     */
    @Async
    @EventListener(classes = UserInfoSingleCollectEvent.class)
    public void onApplicationEvent(UserInfoSingleCollectEvent userInfoSingleCollectEvent) {
        UserInfoCollectType type = userInfoSingleCollectEvent.getType();
        switch (type) {
            case COLLECT_USER_BASE_INFO:
//                System.out.println("开始采集用户基本信息");
                if (userInfoSingleCollectEvent.getUserId()!=null){
                    collectUserBaseInfo((Long.parseLong(userInfoSingleCollectEvent.getUserId().toString())));
                }else {
                    System.out.println("开始采集用户基本信息失败"+ JSONUtil.toJsonStr(userInfoSingleCollectEvent));
                }
                break;
            case COLLECT_USER_VIP_INFO:
//                System.out.println("开始采集用户VIP信息");
                break;
            case COLLECT_USER_SOURCE_CHANEL:
//                System.out.println("开始采集用户来源渠道信息");
                break;
            case COLLECT_USER_GRADE_INFO:
//                System.out.println("开始采集用户学年信息");
                break;
            case COLLECT_USER_TAG_INFO:
//                System.out.println("开始采集用户标签信息");
                break;
            default:
                break;
        }
    }
    /**
     * method : onApplicationEvent
     * description :     用户信息采集事件
     * @param userInfoBatchCollectEvent \{@link UserInfoBatchCollectEvent \}
     * @author : Xiong weiqiang
     * @CreateDate : 2025-04-14 14:42:27
     *
     * @Reviewed :
     * @UpdateLog :    Name    Date    Reason/Contents
     *             ---------------------------------------
     *                ****    ****    ****
     *
     */
    @Async
    @EventListener(classes = UserInfoBatchCollectEvent.class)
    public void onBatchApplicationEvent(UserInfoBatchCollectEvent userInfoBatchCollectEvent) {
        UserInfoCollectType type = userInfoBatchCollectEvent.getType();
        switch (type) {
            case COLLECT_USER_BASE_INFO:
//                System.out.println("开始采集用户基本信息");
                batchCollectUserBaseInfo(userInfoBatchCollectEvent.getUserList());
                break;
            case COLLECT_USER_VIP_INFO:
                System.out.println("开始采集用户VIP信息");
                batchCollectUserVipInfo(userInfoBatchCollectEvent.getUserList());
                break;
            case COLLECT_USER_SOURCE_CHANEL:
                System.out.println("开始采集用户来源渠道信息");
                break;
            case COLLECT_USER_GRADE_INFO:
                System.out.println("开始采集用户学年信息");
                break;
            case COLLECT_USER_TAG_INFO:
                System.out.println("开始采集用户标签信息");
                break;
            default:
                break;
        }
    }
    private void collectUserBaseInfo(Long userId) {
        UserCollectInfo userCollectInfo =userCollectInfoRepository.getUserCollectInfo(userId);
        User user=userRepository.of(userId);
        if (user!=null){
            userCollectInfo.setName(user.getName());
            userCollectInfo.setPhone(user.getPhone());
            userCollectInfo.setGender(user.getGender());
            userCollectInfo.setPhone(user.getPhone());
            userCollectInfo.setRegisterTime(user.getCreateTime());
            userCollectInfo.setLastUpdateTime(new Date());
            //只有更新指定字段
            userCollectInfoRepository.update(Wrappers.lambdaUpdate(UserCollectInfo.class)
                    .eq(UserCollectInfo::getUserId,user.getId())
                    .set(UserCollectInfo::getName,user.getName())
                    .set(UserCollectInfo::getPhone,user.getPhone())
                    .set(UserCollectInfo::getGender,user.getGender())
                    .set(UserCollectInfo::getRegisterTime,user.getCreateTime())
                    .set(UserCollectInfo::getLastUpdateTime,new Date())

            );
        }
    }

    private void batchCollectUserBaseInfo(List<Long> userIds) {
        if (CollUtil.isNotEmpty(userIds)){
            List<User> users=userRepository.getUserList(userIds);
            List<UserCollectInfo> userCollectInfos=userCollectInfoRepository.listByIds(userIds);
            Map<Long,User> userMap=users.stream().collect(Collectors.toMap(User::getId, Function.identity()));
            if (CollUtil.isNotEmpty(userCollectInfos)){
                userCollectInfos.stream().forEach(userCollectInfo -> {
                    User user=userMap.get(userCollectInfo.getUserId());
                    if (user!=null){
                        //只有更新指定字段
                        userCollectInfoRepository.update(Wrappers.lambdaUpdate(UserCollectInfo.class)
                                .eq(UserCollectInfo::getUserId,user.getId())
                                .set(UserCollectInfo::getName,user.getName())
                                .set(UserCollectInfo::getPhone,user.getPhone())
                                .set(UserCollectInfo::getRegisterTime,user.getCreateTime())
                                .set(UserCollectInfo::getGender,user.getGender()==null?0:user.getGender())
                                .set(UserCollectInfo::getLastUpdateTime,new Date())

                        );
                    }
                });
            }
        }
    }


    private void batchCollectUserVipInfo(List<Long> userIds) {
        if (CollUtil.isNotEmpty(userIds)){
            List<DistributeNodeInfo> users=distributeNodeInfoService.list(Wrappers.lambdaQuery(DistributeNodeInfo.class)
                    .in(DistributeNodeInfo::getUserId, userIds).eq(DistributeNodeInfo::getDistributeRoleCode, DistributeSaleRoleEnum.ROLE_SLMB.getCode())
                    .eq(DistributeNodeInfo::getDataStatus,1)
            );
            List<UserCollectInfo> userCollectInfos=userCollectInfoRepository.listByIds(userIds);
            Map<Long,DistributeNodeInfo> userMap=users.stream().collect(Collectors.toMap(DistributeNodeInfo::getUserId, Function.identity()));
            if (CollUtil.isNotEmpty(userCollectInfos)){
                userCollectInfos.stream().forEach(userCollectInfo -> {
                    DistributeNodeInfo user=userMap.get(userCollectInfo.getUserId());
                    if (user!=null){
                        userCollectInfo.setVipScore(0);
                        userCollectInfo.setVipLevel(1);
                        userCollectInfo.setLastUpdateTime(new Date());
                        //只有更新指定字段
                        userCollectInfoRepository.update(Wrappers.lambdaUpdate(UserCollectInfo.class)
                                .eq(UserCollectInfo::getUserId,user.getUserId())
                                .set(UserCollectInfo::getVipLevel,1)
                                .set(UserCollectInfo::getVipScore,0)
                                .set(UserCollectInfo::getLastUpdateTime,new Date()));

                    }
                });
            }
        }
    }
}